﻿@using Fluxor.Blazor.Web.Components;
@using SimpleIdServer.IdServer.Website.Resources;
@using SimpleIdServer.IdServer.Website.Stores.GroupStore;
@using SimpleIdServer.IdServer.Website.Stores.ScopeStore;
@inherits FluxorComponent
@inject Radzen.DialogService dialogService
@inject NotificationService notificationService
@inject IState<GroupRolesState> groupRolesState
@inject IState<UpdateGroupState> updateGroupState
@inject IDispatcher dispatcher

<RadzenDataGrid @ref="grid" 
                AllowFiltering="true"
                AllowColumnResize="true"
                AllowAlternatingRows="false"
                AllowSorting="true"
                PageSize="30"
                AllowPaging="true"
                PagerHorizontalAlign="HorizontalAlign.Left"
                ShowPagingSummary="true"
                IsLoading="@groupRolesState.Value.IsEditableRolesLoading"
                Count="@groupRolesState.Value.EditableGroupCount"
                Data="@groupRolesState.Value.EditableGroupRoles"
                LoadData="@LoadData"
                RowRender="@RowRender"
                TItem="EditableGroupScope"
                ColumnWidth="300px">
    <Columns>
        <RadzenDataGridColumn TItem="EditableGroupScope" Filterable="false" Sortable="false" Width="80px" TextAlign="TextAlign.Center">
            <Template Context="data">
                @if(!data.IsPresent)
                {
                    <RadzenCheckBox @bind-Value=@data.IsSelected Change="@(args => ToggleChanged(args, data))" TValue="bool" />
                }
            </Template>
        </RadzenDataGridColumn>
        <RadzenDataGridColumn TItem="EditableGroupScope" Property="Value.Name" Filterable="false" Sortable="false" Title="@Global.Role" Width="80px" />
        <RadzenDataGridColumn TItem="EditableGroupScope" Property="Value.Description" Filterable="false" Sortable="false" Title="@Global.Description" Width="80px" />
    </Columns>
</RadzenDataGrid>

<RadzenButton Click="@(args => UpdateGroupRoles())" class="mt-1" Variant="Variant.Flat" ButtonType="ButtonType.Submit" ButtonStyle="ButtonStyle.Success" Text="@(updateGroupState.Value.IsUpdating ? Global.Saving : Global.Save)" Disabled="@(updateGroupState.Value.IsUpdating)" />

@code {
    RadzenDataGrid<EditableGroupScope> grid;
    [Parameter]
    public SimpleIdServer.IdServer.Domains.Group Group { get; set; } = null!;

    protected override async Task OnInitializedAsync()
    {
        await base.OnInitializedAsync();
    }

    protected override void OnAfterRender(bool firstRender)
    {
        base.OnAfterRender(firstRender);
        if (firstRender)
        {
            SubscribeToAction<AddGroupRolesSuccessAction>((act) =>
            {
                notificationService.Notify(new NotificationMessage { Severity = NotificationSeverity.Success, Summary = Global.GroupRolesAdded });
                dialogService.Close();
                StateHasChanged();
            });
            grid?.Reload();
        }
    }

    void LoadData(LoadDataArgs args)
    {
        var act = new SearchRoleScopesAction { Filter = args.Filter, OrderBy = args.OrderBy, Skip = args.Skip, Take = args.Top };
        dispatcher.Dispatch(act);
    }

    void ToggleChanged(bool isSelected, EditableGroupScope scope)
    {
        var act = new ToggleRoleScopeSelectionAction { IsSelected = isSelected, ScopeName = scope.Value.Name };
        dispatcher.Dispatch(act);
    }

    void RowRender(RowRenderEventArgs<EditableGroupScope> row)
    {
        const string className = "class";
        if (row.Data.IsSelected)
            row.Attributes.Add(className, "active");
        else if (row.Data.IsPresent)
            row.Attributes.Add(className, "disabled");
        else if (row.Attributes.ContainsKey(className))
            row.Attributes.Remove(className);
    }

    void UpdateGroupRoles()
    {
        var act = new AddGroupRolesAction { GroupId = Group.Id, ScopeNames = groupRolesState.Value.EditableGroupRoles.Where(s => !s.IsPresent && s.IsSelected).Select(s => s.Value.Name) };
        dispatcher.Dispatch(act);
    }
}